package com.leetcode.partition1;

/**
 * @author `RKC`
 * @date 2021/10/19 10:56
 */
public class LC33搜索旋转排序数组 {

    public static int search(int[] nums, int target) {
        //通过二分查找找到最小值的索引
        int minIndex = -1, left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (nums[mid] > nums[right]) {
                left = mid + 1;
            } else if (nums[mid] < nums[right]) {
                right = mid;
            } else {
                right--;
            }
        }
        minIndex = left;
        //相对顺序，旋转后的有序数组第一个元素必定比最后一个元素大，而最后一个元素是第二部分的最大元素，如果target大于最后一个元素
        //查找第一部分；如果target小于第一个元素，查找第二部分
        if (target > nums[nums.length - 1]) {
            //查找第一部分，范围[0, minIndex)
            return binarySearch(nums, 0, minIndex, target);
        } else if (target < nums[0]) {
            //查找第二部分，范围[minIndex, nums.length - 1]
            return binarySearch(nums, minIndex, nums.length - 1, target);
        } else {
            return nums[minIndex] == target ? minIndex : binarySearch(nums, 0, nums.length, target);
        }
    }

    private static int binarySearch(int[] nums, int i, int j, int target) {
        int left = i, right = j;
        while (left <= right) {
            if (left == right && nums[left] != target) break;
            int mid = (left + right) >>> 1;
            if (nums[mid] > target) {
                right = mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3};
        System.out.println(search(nums, 2));
//        int[] nums = {1, 2, 3, 4, 5, 6};
//        System.out.println(binarySearch(nums, 2, nums.length - 1, 1));
    }
}
